﻿using _111.Models;
using Dapper;
using guidHelper;
using Microsoft.AspNetCore.Mvc;
using MyDapperApi.Models;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QYWXUpdate.DataModel;
using QYWXUpdate.DataModel.QYWXCallBack;
using QYWXUpdate.DataModel.QYWXDocument;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using static MyDapperApi.Services.DateBaseService;

namespace MyDapperApi.Services.QywxBase;

public class QywxBaseService : IQywxBaseService
{
    private readonly IConfiguration _configuration;
    private readonly IDateBaseService _dateBaseService;
    private readonly IHttpClientFactory _httpClientFactory;
    //企业微信后台开发者设置的token, corpID, EncodingAESKey
    private readonly string sToken = "NO3Ma17gJk";//企业微信后台，开发者设置的Token
    private readonly string sCorpID = "ww41ce2a97523f4d1a";//企业号corpid是企业号的专属编号（CorpID）[不同场景含义不同，详见文档说明（ToUserName：企业微信的CorpID，当为第三方应用回调事件时，CorpID的内容为suiteid）]
    private readonly string sEncodingAESKey = "lhxbMEwEVPMADwKcC1jpiCSzF7yNkCqiEHwSclqBb0s";//企业微信后台，开发者设置的EncodingAESKey

    public QywxBaseService(IConfiguration configuration, IDateBaseService dateBaseService, IHttpClientFactory httpClientFactory)
    {
        _configuration = configuration;
        _dateBaseService = dateBaseService;
        _httpClientFactory = httpClientFactory;
    }

    /// <summary>
    /// 企业微信标准Post请求<T>
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonGetDocDetailResponse<T>> QywxDocumentPost<T>(StringContent request, string url)
    {
        var result = new CommonGetDocDetailResponse<T>();
        var token = await GetAccessTokenAsync("ww41ce2a97523f4d1a", "xKW0MRSs9azutLLPJt2hDi6gtpYDpdeas5azgxcbUnQ");
        var client = _httpClientFactory.CreateClient();

        var response = new HttpResponseMessage();


        response = await client.PostAsync(
        url + token,
        request);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<CommonGetDocDetailResponse<T>>(res);
                if (wxRespon != null && wxRespon.errcode == 0)
                {
                    result = wxRespon;
                }
                return result;
            }

        }
        response.EnsureSuccessStatusCode();
        return result;
    }

    /// <summary>
    /// 企业微信标准Post请求<T>
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<T> QywxCommonPost<T>(StringContent request, string url) where T : WXResponse, new()
    {
        var result = new T();
        var token = await GetAccessTokenAsync("ww41ce2a97523f4d1a", "xKW0MRSs9azutLLPJt2hDi6gtpYDpdeas5azgxcbUnQ");
        var client = _httpClientFactory.CreateClient();

        var response = new HttpResponseMessage();


        response = await client.PostAsync(
        url + token,
        request);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<T>(res);
                if (wxRespon != null && wxRespon.errcode == 0)
                {
                    result = wxRespon;
                }
                return result;
            }

        }
        response.EnsureSuccessStatusCode();
        return result;
    }

    /// <summary>
    /// 企业微信标准Post请求
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> QywxDocumentPost(StringContent request, string url)
    {
        var result = new CommonResponse();
        var token = await GetAccessTokenAsync("ww41ce2a97523f4d1a", "xKW0MRSs9azutLLPJt2hDi6gtpYDpdeas5azgxcbUnQ");
        var client = _httpClientFactory.CreateClient();

        var response = new HttpResponseMessage();


        response = await client.PostAsync(
        url + token,
        request);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<WXResponse>(res);
                if (wxRespon != null && wxRespon.errcode == 0)
                {
                    result.SetSuccess();
                }
                return result;
            }

        }
        response.EnsureSuccessStatusCode();
        return result;
    }

    /// <summary>
    /// 数据流转String
    /// </summary>
    /// <param name="stream"></param>
    /// <returns></returns>
    public async Task<string> StreamToStringAsync(Stream stream)
    {
        if (stream.CanSeek)
        {
            stream.Seek(0, SeekOrigin.Begin);
        }

        using (StreamReader reader = new StreamReader(stream))
        {
            return await reader.ReadToEndAsync();
        }
    }

    /// <summary>
    /// 获取企业微信token标准方法
    /// </summary>
    /// <param name="corpId"></param>
    /// <param name="secret"></param>
    /// <returns></returns>
    public async Task<string> GetAccessTokenAsync(string corpId, string secret)
    {

        var Secret = AesCbcHelper.Encrypt(secret, System.Text.Encoding.Default.GetBytes("xshAesKey1234567"), System.Text.Encoding.Default.GetBytes("1234567890abcdef"));

        var content = new
        {
            mode = "qywxupdate",
            corpId = corpId,
            secret = Secret
        };

        var client = _httpClientFactory.CreateClient();
        client.DefaultRequestHeaders.Add("ContentType", "application/json");

        var postContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");

        var response = await client.PostAsync("http://ziyan.xshhotels.cn:8687/qwApi/getToken", postContent);


        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await StreamToStringAsync(responseStream);
                var result = JsonConvert.DeserializeObject<TokenResponse>(res);
                if (result != null && result.code == 200)
                {
                    return result.body;
                }
            }

        }
        return "";
    }
}